package www.lagou.app;

import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.MapListHandler;
import org.junit.Test;
import www.lagou.dao.AccountTransfer;
import www.lagou.utils.DruidUtils;

import java.sql.SQLException;
import java.util.List;
import java.util.Map;

/**
 * 测试转账功能。
 */
public class AccountTransferTest {
    /**
     * 测试转账操作对数据库的影响。
     */
    @Test
    public void testAccountTransfer() {
        try {
            System.out.println("# 转账前数据库状态");
            showDatabase();
            System.out.println();

            // 转账。
            System.out.println("# 转账 5000 块...");
            AccountTransfer.transferBalance(1, 2, 5000.0);
            System.out.println();

            System.out.println("# 转账后数据库状态");
            showDatabase();
            System.out.println();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 显示 account 和 transaction 表的数据。
     */
    private static void showDatabase() {
        try {
            QueryRunner runner = new QueryRunner(DruidUtils.getDataSource());

            System.out.println("[account]");
            List<Map<String, Object>> accounts = runner.query("SELECT * FROM account", new MapListHandler());
            for (Map<String, Object> row : accounts) {
                System.out.println(row);
            }

            System.out.println("[transaction]");
            List<Map<String, Object>> transactions = runner.query("SELECT * FROM `transaction`", new MapListHandler());
            for (Map<String, Object> row : transactions) {
                System.out.println(row);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}
